<template>
  <div class="search-page">
    <!-- 顶部搜索栏 -->
    <div class="search-header">
      <van-nav-bar title="搜索" left-arrow @click-left="goBack" />
      <div class="search-input-wrapper">
        <van-search v-model="searchQuery" :show-action="true" action-text="搜索" placeholder="请输入搜索关键词"
          @search="handleSearch" @input="handleInput" />
      </div>
    </div>

    <!-- 历史记录部分 -->
    <div class="history-container" v-if="!isLoadingHistory && historyList.length > 0">
      <div class="history-header">
        <van-cell title="历史搜索" border="false" />
        <van-icon name="delete" size="18px" color="#999" @click="clearAllHistory" />
      </div>
      <div class="history-tags">
        <van-tag v-for="(item, index) in historyList" :key="index" :closable="true" @click="handleHistoryClick(item)"
          class="history-tag">
          {{ item }}
          <!-- 自定义删除按钮 -->
          <van-icon name="cross" class="delete-icon" @click.stop="deleteHistory(index)" />
        </van-tag>
      </div>
    </div>

    <!-- 加载中占位 -->
    <div class="loading-placeholder" v-else-if="isLoadingHistory">
      <van-cell title="加载历史记录..." border="false" />
    </div>

    <!-- 热门搜索 -->
    <div class="hot-container" v-if="!isLoadingHistory && !historyList.length">
      <van-cell title="热门搜索" border="false" />
      <div class="hot-tags">
        <van-tag v-for="(item, index) in hotTags" :key="index" type="primary" @click="handleHotTagClick(item)">
          {{ item }}
        </van-tag>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="result-container" v-if="searchResults.length > 0">
      <van-cell title="搜索结果" border="false" />
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多结果了" @load="onLoad">
        <van-cell v-for="(item, index) in searchResults" :key="index" :title="item.name" :label="item.desc" is-link
          @click="handleResultClick(item)" />
        <van-action-sheet v-model:show="show" :actions="actions" cancel-text="取消" close-on-click-action
          @cancel="onCancel" @select="onSelect" />
      </van-list>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { POST } from "../services/request";
import { showToast } from 'vant';

// 搜索关键词
const searchQuery = ref('');
// 历史记录列表
const historyList = ref([]);
// 加载状态
const loading = ref(false);
const finished = ref(false);
// 搜索结果
const searchResults = ref([]);
// 热门搜索标签
const hotTags = ref([]);
// 用户ID
const userData = ref({}); // 初始化为对象，避免 undefined 报错
const uid = ref('');
// 历史记录加载状态
const isLoadingHistory = ref(false);
// 删除操作状态（防止重复点击）
const isDeleting = ref(false);

// 是否展示二级分类
const show = ref(false);

// 二级分类列表
const actions = ref([]);
// const actions = [
//   { name: '选项一' },
//   { name: '选项二' },
//   { name: '选项三' },
// ];

// 存放搜索结果的数据
const searchData = ref([])

const searchTwoData = ref([])

// 获取用户ID（添加空值处理）
try {
  userData.value = JSON.parse(localStorage.getItem('LoginUser')) || {};
  uid.value = userData.value.id || ''; // 确保 uid 是字符串
} catch (error) {
  console.error('解析用户数据出错:', error);
}

const router = useRouter();

// 初始化：加载历史记录和热门标签
onMounted(async () => {
  await getHistory();
  await getShopTab();
});

// 获取历史记录（添加数据过滤）
const getHistory = async () => {
  isLoadingHistory.value = true;
  historyList.value = []; // 先清空列表

  try {
    const hisRes = await POST({
      url: '/Index/getHistory',
      params: { uid: uid.value }
    });

    if (hisRes.code === 1) {
      // 过滤无效数据，确保 item 包含 skey
      const validData = hisRes.data.filter(item => item && item.skey);
      historyList.value = validData.map(item => item.skey);
    } else {
      showToast(hisRes.msg || '获取历史记录失败');
    }
  } catch (error) {
    console.error('获取历史记录出错:', error);
    showToast('网络错误，请稍后重试');
  } finally {
    isLoadingHistory.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 搜索处理
const handleSearch = async () => {
  const query = searchQuery.value.trim();
  if (query && uid.value) {
    try {
      await POST({
        url: '/Index/searchKey',
        params: { uid: uid.value, skey: query }
      });
      await getHistory();
      // console.log(query);
      await searchResult(query);

      // searchQuery.value = ''; // 清空输入框
    } catch (error) {
      console.error('搜索出错:', error);
      showToast('搜索失败，请稍后重试');
    }
  }
};

// 获取热门标签（添加数据过滤）
const getShopTab = async () => {
  hotTags.value = []; // 先清空标签
  try {
    const getTabRes = await POST({ url: '/Index/getShopTab' });
    if (getTabRes.code === 1) {
      const validTags = getTabRes.data.filter(item => item && item.name);
      hotTags.value = validTags.map(item => item.name);
    }
  } catch (error) {
    console.error('获取热门标签出错:', error);
  }
};

// 输入框防抖处理
let timeoutId = null;
const handleInput = () => {
  clearTimeout(timeoutId);
  timeoutId = setTimeout(() => {
    // 可在此处添加实时搜索逻辑
    // handleSearch()
  }, 300);
};

// 点击历史记录
const handleHistoryClick = (query) => {
  searchQuery.value = query;
  handleSearch();
};

// 点击热门标签
const handleHotTagClick = (tag) => {
  searchQuery.value = tag;
  handleSearch();
};

// 点击搜索结果
const handleResultClick = (item) => {
  show.value = true
  actions.value = []
  searchTwoData.value.forEach(ele=>{
    if(item.id == ele.parent_id){
      actions.value.push(ele)
    }
  })
  // console.log(item);
  // if(it)
  // router.push({ name: 'ProductDetail', params: { id: item.id } });
};

// 删除单条历史记录（关键修复部分）
const deleteHistory = async (index) => {
  // console.log(index);

  if (isDeleting.value) return; // 防止重复点击
  if (index < 0 || index >= historyList.value.length) {
    // clearAllHistory()
    return showToast('记录已删除或不存在');
  }

  const currentList = [...historyList.value]; // 创建当前列表副本
  const skey = currentList[index];

  if (!skey || !uid.value) {
    return showToast('操作失败，请重试');
  }

  isDeleting.value = true; // 锁定删除状态

  try {
    await POST({
      url: '/Index/delOneHistory',
      params: { uid: uid.value, skey }
    });
    // 使用副本索引删除，避免异步操作导致的索引错位
    historyList.value = currentList.filter((_, i) => i !== index);
    searchQuery.value = ''
    searchResults.value = []
    showToast('删除成功');
  } catch (error) {
    console.error('删除失败:', error);
    showToast(error.response?.data?.msg || '删除失败，请稍后重试');
  } finally {
    isDeleting.value = false; // 释放删除状态
  }
};

// 获取搜索词的商品结果
const searchResult = async (query) => {
  const searchRes = await POST({
    url: '/Index/searchKeyShop',
    params: {
      uid: uid.value,
      skey: query
    }
  })
  if (searchRes.code === 1) {
    searchData.value = searchRes.data.oneKeyRes;
    searchTwoData.value = searchRes.data.twoKeyRes;
    console.log(searchRes.data,'searchRes.data.');
    
    if (searchData.value.length > 0) {
      searchResults.value = []
      searchData.value.forEach(item => {
        searchResults.value.push(item)
      })
      // if(searchTwoData.value.length>0){
      //   actions.value = []
      //   searchTwoData.value.forEach(item=>{
      //     actions.value.push(item)
      //   })
      // }
    } else {
      showToast('暂无该分类')
      searchResults.value = []
    }
  } else {
    showToast(searchRes.msg)
    searchResults.value = []
  }
}

// 清空所有历史记录
const clearAllHistory = async () => {

  try {
    const delhisRes = await POST({
      url: '/Index/delHistory',
      params: { uid: uid.value }
    });

    if (delhisRes.code === 1) {
      historyList.value = [];
      showToast(delhisRes.msg);
      await getShopTab();
    } else {
      showToast(delhisRes.msg || '清空失败');
    }
  } catch (error) {
    console.error('清空历史记录出错:', error);
    showToast('网络错误，请稍后重试');
  }
};

// 加载更多
const onLoad = () => {
  setTimeout(() => {
    loading.value = false;
    finished.value = true;
  }, 1000);
};

// 二级分类取消
const onCancel = () => showToast('取消');

// 二级分类列表
// const actions = [
//   { name: '选项一' },
//   { name: '选项二' },
//   { name: '选项三' },
// ];
// 二级分类选择的
const onSelect = (item) => {
  // 默认情况下点击选项时不会自动收起
  // 可以通过 close-on-click-action 属性开启自动收起
  show.value = false;
  showToast(item.name);
  console.log(item);
  
};

</script>

<style scoped>
.search-page {
  height: 100vh;
  background-color: #f7f8fa;
}

.search-header {
  padding: 15px;
  background-color: #fff;
}

.search-input-wrapper {
  margin-top: 10px;
}

.history-container,
.hot-container,
.result-container,
.loading-placeholder {
  margin-top: 15px;
  background-color: #fff;
}

.history-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #f2f3f5;
}

.history-tags,
.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 15px;
}

.history-tag {
  margin-bottom: 10px;
  padding: 6px 12px;
  font-size: 14px;
  background-color: #f5f7fa;
  color: #333;
  transition: all 0.3s ease;
}

.history-tag .van-icon-close {
  font-size: 12px;
  color: #ff4949;
  margin-left: 8px;
}

.history-tag:hover {
  background-color: #f2f3f5;
}

.history-tag:active {
  transform: scale(0.98);
}

.hot-tags .van-tag {
  background-color: #409eff;
  color: white;
}

/* 适配 iPhone X 底部安全区 */
@media (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
  .search-page {
    padding-bottom: 34px;
  }
}
</style>